package chapter12;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/12 11:06
 */
class NeedsCleanup {
    private static long counter = 1;
    private final long id = counter++;

    public void dispose() {
        System.out.println("NeedsCleanup " + id + " dispose");
    }
}

class ConstructionException extends Exception {
}

class NeedsCleanup2 extends NeedsCleanup {
    public NeedsCleanup2() throws ConstructionException {
    }
}

public class CleanupIdiom {
    public static void main(String[] args) {
        // secton 1:
        NeedsCleanup nc1 = new NeedsCleanup();
        try {

        } finally {
            nc1.dispose();
        }

        //section 2:
        NeedsCleanup nc2 = new NeedsCleanup();
        NeedsCleanup nc3 = new NeedsCleanup();
        try {

        } finally {
            nc3.dispose();
            nc2.dispose();
        }

        //section 3:
        try {
            NeedsCleanup2 nc4 = new NeedsCleanup2();
            try {
                NeedsCleanup2 nc5 = new NeedsCleanup2();
                try {
                    //use nc5 nc4
                } finally {
                    nc5.dispose();
                }
            } catch (ConstructionException e) {
                // nc5 constructor
                e.printStackTrace();
            } finally {
                nc4.dispose();
            }
        } catch (ConstructionException e) {
            // nc4 constructor
            e.printStackTrace();
        }
    }
}
